package com.guogee.chart.server;

import com.guogee.chart.handler.ServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/***
 * 区别
 * Bootstrap      用来连接远程主机，有1个EventLoopGroup
 * ServerBootstrap用来绑定本地端口，有2个EventLoopGroup
 * ----------------------------------------------------
 * 	分类 	           |Bootstrap            |	ServerBootstrap
 * ----------------------------------------------------
 *	网络功能                       |连接到远程主机和端口 	 |  绑定本地端口
 *-----------------------------------------------------
 *	EventLoopGroup数量   |数量 	1 	         |   2
 * ----------------------------------------------------
 */

public class MessageServer {
	private int port;

	public MessageServer(int port) {
		this.port = port;
	}

	public void run() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup(); // boss 用来接收进来的连接
		EventLoopGroup workerGroup = new NioEventLoopGroup();// worker用来处理已经被接收的连接
		// 一旦boss接收到连接就会把连接信息注册到worker上
		try {
			//客户端使用Bootstrap  服务端使用ServerBootstrap
			ServerBootstrap b = new ServerBootstrap(); // (2)
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) //指定使用 NIO 的传输 Channel
					.childHandler(new ChannelInitializer<SocketChannel>() { // 添加 ServerHandler 到 Channel 的 ChannelPipeline
						//当一个新的连接被接受，一个新的子 Channel 将被创建， ChannelInitializer 会添加我们ServerHandler
						//的实例到 Channel 的 ChannelPipeline。这个处理器将被通知如果有入站信息
						@Override
								public void initChannel(SocketChannel ch) throws Exception {
									ch.pipeline().addLast(new ServerHandler());
								}
							}).option(ChannelOption.SO_BACKLOG, 128) // (5)
					.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
			// Bind and start to accept incoming connections.
			ChannelFuture f = b.bind(port).sync(); // (7)
			
			// Wait until the server socket is closed.
			// In this example, this does not happen, but you can do that to
			// gracefully
			// shut down your server.
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		int port = 8080;
		new MessageServer(port).run();

	}

}
